package com.googlecode.jmicroerp.wicket.magazin;

import com.googlecode.jmicroerp.model.Magazin;
import com.googlecode.jmicroerp.model.NTipRecipient;
import com.googlecode.jmicroerp.model.Produs;
import com.googlecode.jmicroerp.model.Recipient;
import com.googlecode.jmicroerp.model.Stoc;
import com.googlecode.jmicroerp.repository.GenericOrder;
import com.googlecode.jmicroerp.repository.GenericProperty;
import com.googlecode.jmicroerp.repository.GenericRestriction;
import com.googlecode.jmicroerp.service.GenericService;
import com.googlecode.jmicroerp.service.ProduseService;
import com.googlecode.jmicroerp.service.RecipientService;
import com.googlecode.jmicroerp.wicket.DefaultViewPage;
//import com.googlecode.jmicroerp.wicket.SecuredWebSession;
import com.googlecode.jmicroerp.wicket.administrare.EditareProdusePage;
//import com.googlecode.jmicroerp.wicket.administrare.VizualizareProdusePage;
import com.googlecode.jmicroerp.wicket.components.FileResource;
import com.googlecode.jmicroerp.wicket.components.NameValidator;
import com.googlecode.jmicroerp.wicket.components.RecipientValidator;
import com.googlecode.jmicroerp.wicket.index.IndexPage;
import com.googlecode.jmicroerp.wicket.stocuri.EditareStocPage;
import com.googlecode.jmicroerp.wicket.stocuri.IstoricPage;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
//import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
//import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.lang.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class WizardPage extends DefaultViewPage {
    
    @SpringBean(name = "genericService")
    private GenericService<NTipRecipient> tipRecipientService;
    @SpringBean(name = "genericService")
    private GenericService<Recipient> serviceRecipient;
    @SpringBean(name = "genericService")
    private GenericService<Magazin> magazinService;
    @SpringBean(name = "genericService")
    private GenericService<Produs> produsService;
    @SpringBean(name = "genericService")
    private GenericService<Stoc> stocService;
    @SpringBean(name = "genericService")
    private GenericService<Produs> genericService;
    
    @SpringBean(name = "produseService")
    private ProduseService produseService;
    @SpringBean(name = "recipientService")
    private RecipientService recipientService;
    
    private Magazin magazin;
    private Produs produs; //pt produs existent
    private Produs produs_nou; //pt produs nou
    
    private List<FileUpload> fileUpload;
    @SpringBean(name = "uploadPath")
    private String uploadPath;
    private String denumireP;
    private BigDecimal pretP = BigDecimal.ZERO;
    private static final Logger LOGGER = LoggerFactory.getLogger(EditareProdusePage.class);
    private static final int MAX_SIZE = 1024;
    private String caleImagine = "noimage.jpg";
    
    private NTipRecipient tipRecipient;
    private Recipient recipient;
        
    private String denumire = "C300-ADS";
    private BigDecimal ordine = BigDecimal.ONE;
    private BigDecimal cantitate = BigDecimal.ONE;
  
	private static final long serialVersionUID = 1L;
	//private String numeMag = ((SecuredWebSession) getSession()).getMagazin().getDenumire();
	
    public WizardPage(Long idMagazin) {
    	//magazin = ((SecuredWebSession) getSession()).getMagazin();
    	magazin = magazinService.getById(Magazin.class, idMagazin);
        init();

    }
    
    
    public class StocView extends ListView<Stoc> {

        public StocView(String id, List<Stoc> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Stoc> li) {
            final Stoc stoc = li.getModelObject();
            BigDecimal nivel = stoc.getCantitate().divide(stoc.getRecipient().getTipRecipient().getCapacitateAlerta(), 2, RoundingMode.UP);
            nivel = nivel.multiply(new BigDecimal("100"));
            
            WebMarkupContainer wmc = new WebMarkupContainer("stoc_recipient");
            wmc.add(new AttributeAppender("class", " " + stoc.getRecipient().getTipRecipient().getCategorie().getCodCuloare()));
            
            li.add(new Label("denumire", stoc.getRecipient().getDenumire()));
            
            Label lblActiv = new Label("activ", stoc.getRecipient().isActiv() ? "Activ" : "Inactiv");
            lblActiv.add(new AttributeAppender("class", stoc.getRecipient().isActiv() ? "label label-success" : "label"));
            li.add(lblActiv);
            
            li.add(new Label("nrOrd", stoc.getRecipient().getOrdine()));
            li.add(new Label("stoc", stoc.getCantitate()));
            wmc.add(new Label("nivel", "").add(new AttributeAppender("style", "width: " + nivel + "%;")));
            li.add(wmc);
            Link detailLink = new Link("detailLink") {
                @Override
                public void onClick() {
                    setResponsePage(new IstoricPage((Long) stoc.getRecipient().getId()));
                }
            };
            li.add(detailLink);
            Link editLink = new Link("editLink") {
                @Override
                public void onClick() {
                    setResponsePage(new EditareStocPage((Long) stoc.getId()));
                }
            };
            li.add(editLink);
            
            Link statusLink = new Link("statusLink") {
                @Override
                public void onClick() {
                	
                    Recipient recipient = serviceRecipient.getById(Recipient.class, stoc.getRecipient().getId());
                    recipient.setActiv(recipient.isActiv() ? Boolean.FALSE : Boolean.TRUE);
                    serviceRecipient.update(recipient);                    
                	                    
                    setResponsePage(new WizardPage((Long) magazin.getId()));
                }
            };
            //statusLink.add(new Label )
            li.add(statusLink);
            //li.add(new Label("textLink", "test"));
            
            
            Link LinkUp = new Link("LinkUp") {
                @Override
                public void onClick() {
                	
                    Recipient recipient = serviceRecipient.getById(Recipient.class, stoc.getRecipient().getId());
                    recipient.setOrdine((stoc.getRecipient().getOrdine()).subtract(new BigDecimal(0.1)));
                    serviceRecipient.update(recipient);                    
                	
                    setResponsePage(new WizardPage((Long) magazin.getId()));
                }
            };
            li.add(LinkUp);
            
            Link LinkDown = new Link("LinkDown") {
                @Override
                public void onClick() {
                	
                    Recipient recipient = serviceRecipient.getById(Recipient.class, stoc.getRecipient().getId());
                    recipient.setOrdine((stoc.getRecipient().getOrdine()).add(new BigDecimal(0.1)));
                    serviceRecipient.update(recipient);                    
                	
                    setResponsePage(new WizardPage((Long) magazin.getId()));
                }
            };
            li.add(LinkDown);
        }
    }
    
    private void init() {
    	
    	produs_nou = new Produs();
    	produs_nou.setActiv(Boolean.TRUE);
    	
    	Form<?> form_nou = new Form<Void>("form_nou");
    	//form_nou.setModel(new CompoundPropertyModel<Produs>(produs_nou));
    	
    	final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback_prod");
        form_nou.add(feedbackPanel);
    	
        TextField<String> tfDenumireP = new TextField<String>("denumireP", new PropertyModel<String>(this, "denumireP"));
        tfDenumireP.setRequired(true);
        tfDenumireP.add(new NameValidator(produseService));
        form_nou.add(tfDenumireP);


        TextField<String> tfPretP = new TextField<String>("pretP", new PropertyModel<String>(this, "pretP"));
        tfPretP.setRequired(true);
        form_nou.add(tfPretP);

        
        Image img = new Image("caleImagine", new FileResource(uploadPath, caleImagine)) {
            @Override
            protected boolean shouldAddAntiCacheParameter() {
                return true;
            }
        };
        form_nou.add(img);
        
        final FileUploadField fileUploadField = new FileUploadField("upload", new PropertyModel(this, "fileUpload"));
        form_nou.setMaxSize(Bytes.kilobytes(MAX_SIZE));
        form_nou.add(fileUploadField);

        
//        CheckBox ckActiv = new CheckBox("activP", new ProperyModel(this, Boolean.TRUE ));
//        form_nou.add(ckActiv);

        form_nou.add(new SubmitLink("submitP") {
            @Override
            public void onSubmit() {
            	produs_nou.setDenumire(denumireP);
            	produs_nou.setPret(pretP);
                try {
                    if (fileUpload != null && fileUpload.get(0) != null) {
                        File newFile = new File(uploadPath, fileUpload.get(0).getClientFileName());
                        newFile.createNewFile();
                        fileUpload.get(0).writeTo(newFile);
                        produs_nou.setCaleImagine(fileUpload.get(0).getClientFileName());
                    }
                } catch (IOException ioex) {
                    LOGGER.error("Eroare io", ioex);
                }
                genericService.insert(produs_nou);
                setResponsePage(new WizardPage((Long) magazin.getId()));
            }
        });

        form_nou.add(new Link("cancel") {

            @Override
            public void onClick() {
                setResponsePage(new WizardPage((Long) magazin.getId()));
            }
            
        });
    	
        final Label lbMagazin = new Label("lbMagazin", magazin.getDenumire());
        add(lbMagazin);
        add(new FeedbackPanel("feedback"));
        Form<WizardPage> form = new Form<WizardPage>("form");
        
        recipient = new Recipient();

//        DropDownChoice<Magazin> ddcMagazin = new DropDownChoice<Magazin>(
//        		"magazin", 
//        		new PropertyModel<Magazin>(this, "magazin"),
//        		new LoadableDetachableModel<List<Magazin>>() {
//        			@Override            
//        			protected List<Magazin> load() {
//        				return magazinService.getList(Magazin.class, null, null);
//        			}
//        		}, 
//        		new ChoiceRenderer<Magazin>("denumire", "id"));
//        ddcMagazin.setRequired(true);
        
        DropDownChoice<Produs> ddcProdus = new DropDownChoice<Produs>(
        		"produs", 
        		new PropertyModel<Produs>(this, "produs"),
        		new LoadableDetachableModel<List<Produs>>() {
        			@Override
        			protected List<Produs> load() {
        				List<GenericRestriction> produseActive = new ArrayList<GenericRestriction>();
        				produseActive.add(new GenericRestriction(new GenericProperty("activ"), Boolean.TRUE));
        				List<GenericOrder> produseOrder = new ArrayList<GenericOrder>();
        				produseOrder.add(new GenericOrder(new GenericProperty("ordine"), true));
        				return produsService.getList(Produs.class, produseActive, produseOrder);
        			}
        		}, 
        		new ChoiceRenderer<Produs>("denumire", "id"));
        ddcProdus.setRequired(true);
        
        DropDownChoice<NTipRecipient> ddcNTipRecipient = new DropDownChoice<NTipRecipient>(
        		"tipRecipient", 
        		new PropertyModel<NTipRecipient>(this, "tipRecipient"),
        		new LoadableDetachableModel<List<NTipRecipient>>() {
        			@Override            
        			protected List<NTipRecipient> load() {
        				return tipRecipientService.getList(NTipRecipient.class, null, null);
        			}
        		}, 
        		new ChoiceRenderer<NTipRecipient>("denumire", "id"));
        ddcNTipRecipient.setRequired(true);
        
        TextField<String> tfDenumire = new TextField<String>("denumire", new PropertyModel<String>(this, "denumire"));
        tfDenumire.setRequired(true);
        tfDenumire.add(new RecipientValidator(recipientService, magazin.getId()));
        form.add(tfDenumire);
        
        TextField<BigDecimal> tfOrdine = new TextField<BigDecimal>("ordine", new PropertyModel<BigDecimal>(this, "ordine"));
        tfOrdine.setRequired(true);
        form.add(tfOrdine);
        
        TextField<BigDecimal> tfCantitate = new TextField<BigDecimal>("cantitate", new PropertyModel<BigDecimal>(this, "cantitate"));
        tfCantitate.setRequired(true);
        form.add(tfCantitate);
        
        form.add(new SubmitLink("submit") {

            @Override
            public void onSubmit() {
                recipient.setDenumire(denumire);
                recipient.setMagazin(magazin);
                recipient.setTipRecipient(tipRecipient);
                recipient.setOrdine(ordine);
                recipient.setActiv(Boolean.TRUE);
                
                Stoc stoc = new Stoc();
                stoc.setProdus(produs);
                stoc.setCantitate(cantitate);
                
                recipient.setStoc(stoc);
                stocService.insert(stoc);
                serviceRecipient.insert(recipient);
                stoc.setRecipient(recipient);
                stocService.update(stoc);
                
                info("A fost configurat cu succes Recipientul: " + recipient.getDenumire());
                info ("Poti continua cu adaugarea unui nou Recipient sau renunta...");
                
                setResponsePage(new WizardPage((Long) magazin.getId()));
            }
            
        });
        
        form.add(new Link("renuntare") {

            @Override
            public void onClick() {
                setResponsePage(IndexPage.class);
            }
            
        });
        
        //form.add(ddcMagazin);
        form.add(ddcProdus);
        form.add(ddcNTipRecipient);
        add(form);
        
        
        GenericRestriction rstrMag = new GenericRestriction(new GenericProperty("recipient").setReference(new GenericProperty("magazin").setReference(new GenericProperty("id"))), magazin.getId());
        GenericOrder ordMag = new GenericOrder(new GenericProperty("recipient").setReference(new GenericProperty("ordine")), true);
        
        List<Stoc> stocuri = stocService.getList(Stoc.class, Arrays.asList(rstrMag), Arrays.asList(ordMag));
        add(new Label("lblSize", stocuri.size()));
        
        StocView recipiente = new StocView("recipient", stocuri);
        add(recipiente);
        
        add(form_nou);//produs nou
        
    }
		
}	

